"""
  Copyright (c) 2024 Northeastern University (China)
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
"""
# 任务：这是组件依赖关系构建的主控程序
# 输入：组件识别报告.json的路径
# 输出：组件依赖报告.json

import json
import os
import click

from src.common_utils.utils_file import read_jl_dict, read_jl, write_line_jl
from src.dependency_construction.extraction_feature_dependency import ExtractionFeature
from src.dependency_construction.partition_module import PartitionModule
from src.dependency_construction.build_dependency import BuildDependency

def depbuild(report_path,target_src_path,cpu):
    """构建已识别成分之间依赖关系"""
    components = read_jl(report_path)
    visualization_data=None
    target_src_repo = os.path.basename(target_src_path)
    if len(components) > 1:
        # 划分模块
        partitionModule = PartitionModule()
        module_dic = partitionModule.main(components, target_src_path)
        # 提取特征
        extraction_feature = ExtractionFeature()
        target_features, dependency_dic = extraction_feature.main(module_dic=module_dic,target_src_path=target_src_path,numprocess=cpu)
        # 构建依赖
        buildDependency = BuildDependency()
        final_dependency = buildDependency.build_dependency(dependency_dic, target_features,target_path=target_src_path,numprocess=cpu)
        edges = []
        nodes = [
            {
                'id': 'target_code',
                'repo_name': target_src_repo
            }
        ]
        for data in components:
            repo_name_index = data['name'].rfind("_")
            repo_name = data['name']
            if repo_name_index != -1:
                repo_name = repo_name[:repo_name_index]
            data['id'] = data['name']
            data['repo_name'] = repo_name
            nodes.append(data)
            edges.append({
                'source': 'target_code',
                'target': data['name']
            })
        edges_copy = edges.copy()
        for edge in edges_copy:
            for dep_edge in final_dependency:
                if edge['target'] == dep_edge['target']:
                    if edge in edges:
                        edges.remove(edge)
        edges.extend(final_dependency)
        visualization_data = {'nodes': nodes, 'edges': edges}
    return visualization_data
@click.command()
@click.option('--target_src_path', type=str, required=True, help='Path to target source')
@click.option('--report_path', type=str, default=None, help='Path to component output')
@click.option('--deps_output_path', type=str, default=None, help='Path to component output')
@click.option('--cpu',  type=int, default=8, help='Number of CPU cores')
def main(target_src_path,report_path,deps_output_path,cpu):
    target_src_repo = os.path.basename(target_src_path)
    visualization_data=depbuild(target_src_path=target_src_path,report_path=report_path,cpu=cpu)
    if deps_output_path is not None:
        with open(os.path.join(deps_output_path, target_src_repo + '_deps.json'), "w") as json_file:
            json.dump(visualization_data, json_file)
    print(f"depsdata={visualization_data}")

if __name__ == "__main__":
  main()